#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2025 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import re
import json
import logging
from utils import utils_data, ErrorInfoBuilder

logger = logging.getLogger('my_logger')


def find_block_end(content, start_index):
    open_braces = 1
    for i in range(start_index, len(content)):
        line = content[i]
        open_braces += line.count('{')
        open_braces -= line.count('}')
        if open_braces == 0:
            return i + 1
    return len(content)


def check_partname():
    file_entities = utils_data.get_file()
    if not file_entities:
        logger.error("未获取到文件信息")
        return

    has_error = False

    for file_entity in file_entities:
        if file_entity.file_name == "BUILD.gn":
            file_path = file_entity.full_path
            with open(file_path, 'r', encoding='utf-8') as file:
                content = file.readlines()
                target_pattern = re.compile(r'(ohos_app_assist_suite|ohos_js_app_suite|ohos_js_hap_suite|ohos_testsuite_base|ohos_moduletest_suite|ohos_hap_suite|ohos_shell_app_suite|ohos_prebuilt_suite|ohos_deploy_xdevice|ohos_test_suite|pythontest_suite|executable_suite|js_hap_suite|ohos_hap_assist_suite|ohos_sh_assist_suite|merge_xts_notice)\s*\(')

                for i, line in enumerate(content, start=1):
                    target_match = target_pattern.search(line)
                    if target_match:
                        start_index = i
                        end_index = find_block_end(content, start_index)
                        block_content = ''.join(content[start_index - 1:end_index])
                        part_name_match = re.search(r'part_name\s*=\s*"(.+?)"', block_content)
                        subsystem_name_match = re.search(r'subsystem_name\s*=\s*"(.+?)"', block_content)

                        if not part_name_match or not subsystem_name_match:
                            error_info = ErrorInfoBuilder() \
                                .set_buggy_file_path(file_entity.file_path) \
                                .set_defect_type("XTS.CHECK.PARTNAME.01") \
                                .set_description("gn文件必须配置part_name和subsystem_name字段") \
                                .set_main_buggy_line(start_index) \
                                .set_main_buggy_code(line.strip()) \
                                .build()

                            utils_data.write_error_to_json_file(error_info)
                            logger.info(json.dumps(error_info, indent=4, ensure_ascii=False))
                            has_error = True

    if has_error:
        logger.info("part_name、subsystem_name配置检查完成，错误信息已写入xts_result.json")
    else:
        logger.info("part_name、subsystem_name配置检查通过")



